<!-- src\views\house\List.vue -->
<template>
  <div class="page-container">
    <!-- 未租出 -->
    <div v-if="housesByStatus['1'].length > 0" class="status-section">
      <h3>未租出</h3>
      <el-table :data="housesByStatus['1']" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="city" label="城市"></el-table-column>
        <el-table-column prop="rentType" label="租赁类型"></el-table-column>
        <el-table-column prop="monthRent" label="租金"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              @click="updateStatus(scope.row, 2)"
              type="primary"
            >
              租出
            </el-button>
            <el-button
              size="small"
              @click="updateStatus(scope.row, 3)"
              type="warning"
            >
              下架
            </el-button>
            <el-button
              size="small"
              @click="deleteHouse(scope.row)"
              type="danger"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 已租出 -->
    <div v-if="housesByStatus['2'].length > 0" class="status-section">
      <h3>已租出</h3>
      <el-table :data="housesByStatus['2']" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="city" label="城市"></el-table-column>
        <el-table-column prop="rentType" label="租赁类型"></el-table-column>
        <el-table-column prop="monthRent" label="租金"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              @click="updateStatus(scope.row, 1)"
              type="info"
            >
              取消租出
            </el-button>
            <el-button
              size="small"
              @click="deleteHouse(scope.row)"
              type="danger"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 已下架 -->
    <div v-if="housesByStatus['3'].length > 0" class="status-section">
      <h3>已下架</h3>
      <el-table :data="housesByStatus['3']" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="city" label="城市"></el-table-column>
        <el-table-column prop="rentType" label="租赁类型"></el-table-column>
        <el-table-column prop="monthRent" label="租金"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              @click="updateStatus(scope.row, 1)"
              type="success"
            >
              上架
            </el-button>
            <el-button
              size="small"
              @click="deleteHouse(scope.row)"
              type="danger"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 已删除 -->
    <div v-if="housesByStatus['-1'].length > 0" class="status-section">
      <h3>已删除</h3>
      <el-table :data="housesByStatus['-1']" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="city" label="城市"></el-table-column>
        <el-table-column prop="rentType" label="租赁类型"></el-table-column>
        <el-table-column prop="monthRent" label="租金"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              @click="restoreHouse(scope.row)"
              type="warning"
            >
              恢复
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 待审核 -->
    <div v-if="housesByStatus['-2'].length > 0" class="status-section">
      <h3>待审核</h3>
      <el-table :data="housesByStatus['-2']" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="city" label="城市"></el-table-column>
        <el-table-column prop="rentType" label="租赁类型"></el-table-column>
        <el-table-column prop="monthRent" label="租金"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              @click="approveHouse(scope.row)"
              type="success"
            >
              审核通过
            </el-button>
            <el-button
              size="small"
              @click="rejectHouse(scope.row)"
              type="danger"
            >
              审核不通过
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 审核不通过 -->
    <div v-if="housesByStatus['-3'].length > 0" class="status-section">
      <h3>审核不通过</h3>
      <el-table :data="housesByStatus['-3']" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="city" label="城市"></el-table-column>
        <el-table-column prop="rentType" label="租赁类型"></el-table-column>
        <el-table-column prop="monthRent" label="租金"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import api from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";

const pagination = ref({
  page: 1,
  size: 10,
  total: 0,
});

const houses = ref([]);
const housesByStatus = ref({
  1: [],
  2: [],
  3: [],
  "-1": [],
  "-2": [],
  "-3": [],
});

async function fetchHouses() {
  try {
    const params = {
      page: pagination.value.page,
      size: pagination.value.size,
    };

    const response = await api.house.getHouses(params);

    if (response.data?.data) {
      houses.value = response.data.data;
      pagination.value.total = response.data.total;
      groupHousesByStatus();
    }
  } catch (error) {
    console.error("数据加载失败:", error);
    ElMessage.error("数据加载失败: " + error.message);
  }
}

function groupHousesByStatus() {
  const init = () => ({ 1: [], 2: [], 3: [], "-1": [], "-2": [], "-3": [] });
  housesByStatus.value = init();

  if (!Array.isArray(houses.value)) return;

  houses.value.forEach((house) => {
    const status = String(house?.status || 1);
    housesByStatus.value[status]?.push(house);
  });
}

onMounted(() => {
  fetchHouses();
});

async function updateStatus(row, newStatus) {
  try {
    await ElMessageBox.confirm(
      `确认要将【${row.title}】的状态变更为【${getStatusText(newStatus)}】吗？`,
      "操作确认",
      { type: "warning" }
    );

    const houseId = Number.isNaN(row.id) ? 0 : parseInt(row.id, 10);

    const statusCode = Number.isNaN(newStatus)
      ? 1 // 默认回退到未租出
      : parseInt(newStatus, 10);

    // 添加参数验证
    if (isNaN(houseId) || isNaN(statusCode)) {
      throw new Error("参数格式错误");
    }

    await api.house.updateStatus(houseId, statusCode);

    // 更新本地数据
    row.status = statusCode;
    groupHousesByStatus();

    ElMessage.success("状态更新成功");
  } catch (error) {
    if (error !== "cancel") {
      const msg = error.response?.data?.message || error.message;
      ElMessage.error(`操作失败: ${msg}`);
    }
  }
}
async function deleteHouse(row) {
  try {
    await updateStatus(row, -1); // 将房屋状态设置为已删除
  } catch (error) {
    console.error("删除房屋失败:", error);
    ElMessage.error(error.response?.data?.message || "操作失败");
  }
}

async function restoreHouse(row) {
  try {
    await updateStatus(row, 1); // 将房屋状态设置为未租出
  } catch (error) {
    console.error("恢复房屋失败:", error);
    ElMessage.error(error.response?.data?.message || "操作失败");
  }
}

async function approveHouse(row) {
  try {
    await updateStatus(row, 1); // 将房屋状态设置为未租出
  } catch (error) {
    console.error("审核通过失败:", error);
    ElMessage.error(error.response?.data?.message || "操作失败");
  }
}

async function rejectHouse(row) {
  try {
    await updateStatus(row, -3); // 将房屋状态设置为审核不通过
  } catch (error) {
    console.error("审核不通过失败:", error);
    ElMessage.error(error.response?.data?.message || "操作失败");
  }
}

function getStatusText(status) {
  switch (status) {
    case 1:
      return "未租出";
    case 2:
      return "已租出";
    case 3:
      return "已下架";
    case -1:
      return "已删除";
    case -2:
      return "待审核";
    case -3:
      return "审核不通过";
    default:
      return "未知状态";
  }
}

function getStatusTagType(status) {
  switch (status) {
    case 1:
      return "success";
    case 2:
      return "primary";
    case 3:
      return "warning";
    case -1:
      return "danger";
    case -2:
      return "info";
    case -3:
      return "danger";
    default:
      return "";
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.status-section {
  margin-bottom: 20px;
}

.el-table th {
  background-color: #f5f7fa;
}

.el-table__row {
  height: 48px;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}
</style>
